package 周赛._283;

import java.util.HashMap;
import java.util.Map;

public class _6018_根据描述创建二叉树 {
    public TreeNode createBinaryTree(int[][] descriptions) {
        int n = descriptions.length;
        TreeNode root = null;
        TreeNode parent = null;
        TreeNode node = null;
        int index = 0;
        Map<Integer, TreeNode> hash = new HashMap<>();
        Map<TreeNode, TreeNode> parents = new HashMap<>();
        for (int[] description : descriptions) {
            int p = description[0];
            int c = description[1];
            if (hash.containsKey(p)) {
                parent = hash.get(p);
            } else {
                parent = new TreeNode(p);
                hash.put(p, parent);
            }
            if (hash.containsKey(c)) {
                node = hash.get(c);
            } else {
                node = new TreeNode(c);
                hash.put(c, node);
            }
            if (description[2] == 1) {
                parent.left = node;
            } else {
                parent.right = node;
            }
            if (!parents.containsKey(parent)) {
                parents.put(parent, null);
            }
            parents.put(node, parent);
        }
        for (Map.Entry<TreeNode, TreeNode> entry : parents.entrySet()) {
            if (entry.getValue() == null) {
                root = entry.getKey();
                break;
            }
        }
        return root;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
